//
//  MyDocument.m
//  Documents
//
//  Created by Alex Di Mango 
//  Copyright (c) 2012 Whardoo.com -  All rights reserved.
//

#import "MyDocument.h"
#import "MyDocumentsFolder.h"
#import "AppDelegate.h"
#import "DocumentsCache.h"
#import "DocumentsConstants.h"

@implementation MyDocument

@dynamic documentId;
@dynamic author;
@dynamic title;
@dynamic filePath;
@dynamic fileType;
@dynamic size;
@dynamic updateDate;
@dynamic myFolder;
@dynamic marked;
@dynamic image,imageRef;
@dynamic sideImage,sideImageRef;

+(MyDocument *)getDocumentWithId:(NSNumber *)documentId
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyDocument" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"documentId == %@", documentId];
    [request setPredicate:predicate];
    NSError *errors = nil;
    NSArray *resultArray = [managedObjectContext executeFetchRequest:request error:&errors];
    [request release];
    if([resultArray count] == 0)
        return nil;
    MyDocument *result = [resultArray objectAtIndex:0];
    return result;
}

+(void)deleteSelectedDocument:(MyDocument *)myDocument
{    
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
        [DocumentsCache removeFromCache:myDocument];
        [managedObjectContext deleteObject:myDocument];
    [appDelegate saveContext];    
}

+(NSArray *)getDocumentListForFolderId:(NSNumber *)folderId
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyDocument" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myFolder.folderId == %@", folderId];
    [request setPredicate:predicate];
    
    NSError *errors = nil;
    NSArray *result = [managedObjectContext executeFetchRequest:request error:&errors];
    [request release];
    return result;
}

+(NSArray *)myDocuments
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyDocument" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"updateDate" ascending:FALSE];
    [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

    NSError *errors = nil;
    NSArray *result = [managedObjectContext executeFetchRequest:request error:&errors];
    [request release];
    [sortDescriptor release];
    
    return result;
}


+(MyDocument *)getDocumentWithName:(NSString *)documentName
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyDocument" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", documentName];
    [request setPredicate:predicate];
    
    
    NSError *errors = nil;
    NSArray *resultArray = [managedObjectContext executeFetchRequest:request error:&errors];
    [request release];
    if([resultArray count] == 0)
        return nil;
    MyDocument *result = [resultArray objectAtIndex:0];
    return result;

}

+(NSNumber *)getMaxDocumentId{    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
    //Entity
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyDocument" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];
    
    request.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"documentId"]];
//    request.resultType = NSDictionaryResultType;
    
    
    NSError *errors = nil;
    NSArray *result = [managedObjectContext executeFetchRequest:request error:&errors];
    [request release];
    return [result valueForKeyPath:@"@max.documentId"];                          
}


// add new document in object context and write a copy in doc_folder
+(MyDocument *) addDocument: (NSURL *) url
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
    MyDocument *myDocument = (MyDocument *)[NSEntityDescription insertNewObjectForEntityForName:@"MyDocument" inManagedObjectContext: managedObjectContext];
    //get url info
    NSString *path = [url absoluteString];
    NSArray *lastChild = [[path lastPathComponent] componentsSeparatedByString:@"."];
    NSString *last = [lastChild lastObject];
    NSString *name = [path lastPathComponent];
    NSString *t = [[[path lastPathComponent]substringToIndex:[name length]-([last length]+1)]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;
    NSString *extension = last; 
    //set MyDocument id = max +1

    NSNumber *myDocId = [NSNumber numberWithInteger:[[MyDocument getMaxDocumentId] intValue] +1];    
    NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];  
    NSString  *destination = [NSString stringWithFormat:@"%@/%@/%@.%@", documentsDirectory, MYDOCUMENTS,[myDocId stringValue],extension];
    NSString  *localPath = [NSString stringWithFormat:@"%@/%@.%@", MYDOCUMENTS,[myDocId stringValue],extension];
    NSData *stream = [NSData dataWithContentsOfURL:url]; 
    [stream writeToFile:destination atomically:YES];
    //set document properties
    [myDocument setDocumentId:myDocId];
    [myDocument setTitle:t];
    [myDocument setFileType:extension];
    [myDocument setFilePath:localPath];
    [myDocument setMyFolder:[MyDocumentsFolder getDefaultFolder]];
    [myDocument setSize:[NSNumber numberWithInteger:[stream length]/1024]];
    [myDocument setUpdateDate:[NSDate date]];
    return myDocument;
}

+(NSArray *)getDocumentListWithName:(NSString *)name forFolder:(NSNumber *)folderId orderBy:(NSString *)orderingField ascending:(BOOL)ascending
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
    //Entity
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyDocument" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];
    //Predicate
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myFolder.folderId == %@", folderId];
    [request setPredicate:predicate];
    if(name != nil && ![name isEqualToString:@""])
    {
        NSPredicate *folderPredicate = [NSPredicate predicateWithFormat:@"myFolder.folderId == %@", folderId];
        NSPredicate *titlePredicate = [NSPredicate predicateWithFormat:@"title CONTAINS[cd] %@", name];
        NSArray *subPredicates = [NSArray arrayWithObjects:folderPredicate, titlePredicate, nil];
        predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
    }
    [request setPredicate:predicate];
    //SortDescriptor
    NSSortDescriptor *sortDescriptor = nil;
    if(orderingField == @"title")
    {
        sortDescriptor = [[NSSortDescriptor alloc] initWithKey:orderingField ascending:ascending selector:@selector(localizedCaseInsensitiveCompare:)];
    }
    else 
    {
        sortDescriptor = [[NSSortDescriptor alloc] initWithKey:orderingField ascending:ascending];
    }
    [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    
    NSError *errors = nil;
    NSArray *result = [managedObjectContext executeFetchRequest:request error:&errors];
    [request release];
    [sortDescriptor release];
    return result;
    
}

-(NSString *)localDocPath
{
    NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];  
    return [NSString stringWithFormat:@"%@/%@/%@.%@", documentsDirectory, MYDOCUMENTS, [self.documentId stringValue],self.getFileType];
}


#pragma mark - DocumentProtocol
-(NSString *)getFolderName
{
    return self.myFolder.name;
}

-(NSString *)getDocumentTitle
{
    return self.title;
}

-(NSNumber *)getFileId
{
    return self.documentId;
}

-(NSString *)getDocumentPath
{
    return self.filePath;
}

-(NSString *)getFileType
{
    return self.fileType;
}

@end
